# functions.mk - Miscellaneous functions.
# Copyright (C) 2007  Mikhail Vorozhtsov
# See the LICENSE section of the README file for details.

# $Id$

extract-arch = $(shell echo $(1) | sed -e 's/^\([^-]\+\)-[^-]\+$$/\1/')
extract-platform = $(shell echo $(1) | sed -e 's/^[^-]\+-\([^-]\+\)$$/\1/')

lower-case = $(shell echo $(1) | tr [:upper:] [:lower:])
upper-case = $(shell echo $(1) | tr [:lower:] [:upper:])

if-file-exists = $(shell test -f $(1) 2>/dev/null && echo $(1) || echo $(2))

prefix-src = $(foreach src,$(2),sources/$(1)/$(src))

arch-src = $(call prefix-src,$(ARCH),$(1))
platform-src = $(call prefix-src,$(PLATFORM),$(1))
machine-src = $(call prefix-src,$(ARCH)/$(PLATFORM),$(1))

prefix-arch-src = $(call prefix-src,$(1)/$(ARCH),$(2))
prefix-platform-src = $(call prefix-src,$(1)/$(PLATFORM),$(2))
prefix-machine-src = $(call prefix-src,$(1)/$(ARCH)/$(PLATFORM),$(2))

subst-dir = \
  $(foreach f,$(3),$(if $(f:$(1)/%=), \
                        $(shell echo $(f) | sed -e "s,/$(1)/,/$(2)/,"), \
                        $(f:$(1)/%=$(2)/%)))
subst-dirs = \
  $(if $(strip $(1)), \
       $(call subst-dir,$(word 1,$(1)),$(word 2,$(1)), \
                        $(call subst-dirs, \
                                 $(filter-out $(word 1,$(1)) $(word 2,$(1)), \
                                              $(1)), \
                                 $(2))), \
       $(2))

